package com.example.login.service;
import com.example.login.mapper.UserMapper;
import com.example.login.entity.Result;
import com.example.login.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.login.util.JwtUtil.createToken;
import static com.example.login.util.JwtUtil.verifyToken;

//实现
@Service
public class UserServiceImp implements UserService{

    @Autowired
    private UserMapper ud; //可以直接调用UserDao的所有方法


    @Override
    public User findUserByUsername(String mobile){
    //public LinkedList<User> findUserByUsername(String mobile){
        LinkedList<User> ans =new LinkedList<User>();
        ans.add(ud.findUserByUsername(mobile));
        System.out.println("成功通过findUserByUsername,user列表为"+ans.toString());
        return ud.findUserByUsername(mobile);
    }

    @Override
    public Map<String, String> getUserInfoByMobile(String mobile) {
        return ud.getUserInfoByMobile(mobile);
    }

    //使用md5加密
    private static String md5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");

            byte[] bytes = md.digest(password.getBytes());

            String str = Base64.getEncoder().encodeToString(bytes);

            return str;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    //登录
    public Result login(HttpServletRequest request, HttpServletResponse response, Map<String, String> loginInfo){
        String mobile = loginInfo.get("mobile");
        String password = loginInfo.get("password");
        User u = new User();
        u.setMobile(mobile);
        u.setPassword(password);
        System.out.println("登陆检查");
        Result result = new Result();
        try{
            //检查数据是否合法
            //判断手机号是否满足要求
            String regex1 = "^[1][3,4,5,7,8][0-9]{9}$";
            Pattern p = Pattern.compile(regex1);
            Matcher m = p.matcher(u.getMobile());
            System.out.println("开始手机号检查");
            if(!m.matches()){
                //手机号不符合要求
                System.out.println("手机号不符合要求");
                result.setStatus(500);
                result.setMsg("验证失败，手机号或密码不正确");
                System.out.println("验证失败，手机号或密码不正确");
            }
            else{
                User existUser;
                System.out.println("用户身份检查");
                try{
                    System.out.println("mobile "+u.getMobile());
                    //LinkedList<User> userList = findUserByUsername(u.getMobile());
                    //System.out.println("****************userList.getFirst()"+userList.getFirst());
                    existUser = findUserByUsername(u.getMobile());
                    System.out.println("应该没有异常"+existUser.toString());
                }catch (Exception e){
                    e.printStackTrace();
                    result.setStatus(500);
                    System.out.println("用户身份不符合要求");
                    result.setMsg("验证失败");
                    System.out.println(e);
                    System.out.println("验证失败");
                    return result;
                }

                String newPasswd = md5(md5(u.getPassword()));
                if(existUser == null)
                {
                    //用户名不存在
                    result.setStatus(500);
                    result.setMsg("验证失败，该手机号未注册");
                }else if(!existUser.getPassword().equals(newPasswd)){
                    //密码不符合要求
                    result.setStatus(500);
                    result.setMsg("验证失败，密码不正确");
                }
                else{
                    //成功登录
                    result.setStatus(1);
                    System.out.println("成功登录");
                    result.setMsg("登录成功");

//                    HttpHeaders headers = new HttpHeaders();
//                    headers.set("Content-Type","application/json");
                    //String token = restTemplate.postForObject("http://localhost:8092/jwt/getToken", new HttpEntity<>(loginInfo,headers),String.class);
                    String token =createToken(existUser);
                    //可以使用Map接口获取键值的存储
                    Map<String,Object> dataInfo = new HashMap<>();
                    dataInfo.put("token", token);
                    dataInfo.put("uid", existUser.getId());
                    result.setData(dataInfo);
                }
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        System.out.println("验证结束");
        return result;
    }

    //验证jwt,在Jwtutil中实现了
//    public Boolean verifyToken(Map<String, String> queryInfo){
//        HttpHeaders headers = new HttpHeaders();
//        Map<String,String> body = new HashMap<>();
//        body.put("token", queryInfo.get("token"));
//        return restTemplate.postForObject("http://localhost:8092/jwt/testToken",new HttpEntity<>(body, headers), Boolean.class);
//    }

    public Result getUserInfo(HttpServletRequest request, HttpServletResponse response, Map<String, String> reqInfo){
        Result result = new Result();
        //验证token是否正确
        if(!verifyToken(reqInfo.get("token"))){
            result.setStatus(500);
            result.setMsg("用户未登录，请重新登录");
            return result;
        }
        //根据mobile查询所有信息
        try{
            Map<String, String> userInfo = getUserInfoByMobile(reqInfo.get("mobile"));
            result.setStatus(1);
            result.setMsg("成功返回用户信息");
            result.setData(userInfo);

        }catch (Exception e){
            result.setStatus(500);
            result.setMsg("无法获取参数");
            System.out.println(e);
        }
        return result;
    }

}
